<?php
/**
 * Created by PhpStorm.
 * User: 秋枫雁飞
 * Date: 2019/3/28
 * Time: 11:53
 */

namespace Aiweline\Core\Helper;

use Magento\Framework\App\ResourceConnection;


class Db
{
    /*链接区*/
    private $_objectManager;//对象管理器
    private $_resource;     //资源
    private $link;           //数据库连接句柄
    /*字段区*/
    private $_table = null;//表名
    private $_where = null;//where条件
    private $_order = null;//order排序
    private $_limit = null;//limit限定查询
    private $_group = null;//group分组

    function __construct(
        ResourceConnection $connection
    )
    {
        $this->_resource = $connection;
        $this->_link = $connection->getConnection(\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION);
    }


    /**
     * [getAll 获取所有数据]
     * @param string $table [表名]
     * @return array        [结果集:boolean array]
     */
    public function getAll($table = null)
    {
        $table = $table ? $table : $this->_table;
        $link = $this->_link;
        if (!$link) return false;
        $sql = "SELECT * FROM {$table}";
        $data = $this->execute($sql);
        return $data;
    }

    /**
     * 获得带表前缀的表名
     * @param $table
     * @return string
     */
    public function getTableName($table)
    {
        return $this->_resource->getTableName($table);
    }

    /**
     * [table 设置查询表]
     * @param string $table [表名]
     * @return mixed         [当前对象]
     */
    public function table($table)
    {
        $this->_table = $this->_resource->getTableName($table);
        return $this;
    }

    /**
     * [select 选择查询]
     * @param string $fields [字段]
     * @return mixed         [结果集]
     */
    public function select($fields = "*")
    {
        $fieldsStr = '';
        $link = $this->_link;
        if (!$link) return false;
        if (is_array($fields)) {
            $fieldsStr = implode(',', $fields);
        } elseif (is_string($fields) && !empty($fields)) {
            $fieldsStr = $fields;
        }
        $sql = "SELECT {$fieldsStr} FROM {$this->_table} {$this->_where} {$this->_order} {$this->_limit}";
        return $this->_link->fetchAll($sql);
    }

    /**
     * [selectOne 选择查询]
     * @param string $fields [字段]
     * @return mixed         [结果集]
     */
    public function selectOne($fields = "*")
    {
        $fieldsStr = '';
        $link = $this->_link;
        if (!$link) return false;
        if (is_array($fields)) {
            $fieldsStr = implode(',', $fields);
        } elseif (is_string($fields) && !empty($fields)) {
            $fieldsStr = $fields;
        }
        $sql = "SELECT {$fields} FROM {$this->_table} {$this->_where} {$this->_order} {$this->_limit}";
        return $this->_link->fetchOne($sql);
    }

    /**
     * [order 排序]
     * @param string $order [排序规则]
     * @return mixed        [当前对象]
     */
    public function order($order = '')
    {
        $orderStr = '';
        $link = $this->_link;
        if (!$link) return false;
        if (is_string($order) && !empty($order)) {
            $orderStr = "ORDER BY " . $order;
        }
        $this->_order = $orderStr;
        return $this;
    }

    /**
     * [where 条件查询]
     * @param string $where [查询条件]
     * @return mixed        [当前对象]
     */
    public function where($where = '')
    {
        $whereStr = '';
        $link = $this->_link;
        if (!$link) return $link;
        if (is_array($where)) {
            end($where);
            $last_key = key($where);
            foreach ($where as $key => $value) {
                if ($key == $last_key) {
                    $whereStr .= "`" . $key . "` = '" . $value . "'";
                } else {
                    $whereStr .= "`" . $key . "` = '" . $value . "' AND ";
                }
            }
            $whereStr = "WHERE " . $whereStr;
        } elseif (is_string($where) && !empty($where)) {
            $whereStr = "WHERE " . $where;
        }
        $this->_where = $whereStr;
        return $this;
    }

    /**
     * [group 分组查询]
     * @param string $group [分组条件]
     * @return mixed        [当前对象]
     */
    public function group($group = '')
    {
        $groupStr = '';
        $link = $this->_link;
        if (!$link) return false;
        if (is_array($group)) {
            $groupStr = "GROUP BY " . implode(',', $group);
        } elseif (is_string($group) && !empty($group)) {
            $groupStr = "GROUP BY " . $group;
        }
        $this->_group = $groupStr;
        unset($groupStr);
        return $this;
    }

    /**
     * [limit 限制查询]
     * @param string $limit [限制条件]
     * @return mixed        [当前对象]
     */
    public function limit($limit = '')
    {
        $limitStr = '';
        $link = $this->_link;
        if (!$link) return $link;
        if (is_string($limit) || !empty($limit)) {
            $limitStr = "LIMIT " . $limit;
        } elseif (is_numeric($limit)) {
            $limitStr = "LIMIT " . $limit;
        }
        $this->_limit = $limitStr;
        return $this;
    }

    /**
     * [execute 查询执行]
     * @param string $sql [SQL结构化查询语句]
     * @return mixed      [结果集]
     */
    public function execute($sql = null)
    {
        $link = $this->_link;
        if (!$link) return false;
        //$res = mysqli_query($this->_link,$sql);
        $res = $this->_link->query($sql);
//         if (!$res) {
// //            $errors = mysqli_error_list($this->_link);
//             // $this->ShowException("空结果！");
//             return [];
//         }
        return $res;
    }

    /**
     * [insert 记录插入]
     * @param array $data [插入数组]
     * @return mixed       [插入结果：boolean]
     */
    public function insert($data)
    {
        $link = $this->_link;
        if (!$link) return false;
        if (is_array($data)) {
            $keys = '';
            $values = '';
            foreach ($data as $key => $value) {
                $keys .= "`" . $key . "`,";
                $values .= "'" . $value . "',";
            }
            $keys = rtrim($keys, ',');
            $values = rtrim($values, ',');
        }
        $sql = "INSERT INTO `{$this->_table}`({$keys}) VALUES({$values})";
        return $this->execute($sql);
    }

    /**
     * [update 更新数据]
     * @param array $data [更新数据组]
     * @return mixed       [更新结果]
     */
    public function update($data)
    {
        $link = $this->_link;
        if (!$link) return $link;
        if (is_array($data)) {
            $dataStr = '';
            foreach ($data as $key => $value) {
                $dataStr .= "`" . $key . "`='" . $value . "',";
            }
            $dataStr = rtrim($dataStr, ',');
        }
        $sql = "UPDATE `{$this->_table}` SET {$dataStr} {$this->_where} {$this->_order} {$this->_limit}";
        $res = $this->execute($sql);
        return $res;
    }

    /**
     * [delete 删除数据]
     * @return mixed [删除结果]
     */
    public function delete()
    {
        $link = $this->_link;
        if (!$link) return $link;
        $sql = "DELETE FROM `{$this->_table}` {$this->_where}";
        $res = $this->execute($sql);
        return $res;
    }

    /**
     * [buildSql 构建查询语句]
     * @return string [sql]
     */
    public function buildSql()
    {
        return "功能暂未实现！";
    }

    /**
     * [ShowException 异常信息输出]
     * @param string $var [异常信息]
     */
    private function ShowException($var)
    {
        if (is_bool($var)) {
            var_dump($var);
        } else if (is_null($var)) {
            var_dump(NULL);
        } else {
            echo "<pre style='position:relative;z-index:1000;padding:10px;border-radius:5px;background:#F5F5F5;border:1px solid #aaa;font-size:14px;line-height:18px;opacity:0.9;'>" . print_r($var, true) . "</pre>";
        }
    }
}